package com.landiao.service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import com.landiao.common.Constant;
import com.landiao.common.Constant.PayResult;
import com.landiao.common.factory.ResultMsgFactory;
import com.landiao.common.pojo.Page;
import com.landiao.common.pojo.Querier;
import com.landiao.common.pojo.ResultMsg;
import com.landiao.common.utils.CodecUtils;
import com.landiao.common.utils.DateUtil;
import com.landiao.common.weixin.WxMpService;
import com.landiao.common.weixin.bean.WxMpPayOrderQuery;
import com.landiao.entities.NoteDict;
import com.landiao.entities.OrderInfo;
import com.landiao.entities.PayFlow;
import com.landiao.mapper.NoteDictMapper;
import com.landiao.mapper.OrderInfoMapper;
import com.landiao.mapper.PayFlowMapper;
import com.landiao.mapper.VipMapper;

/**
 * 功能说明:
 */
@Service
public class PayFlowService extends BaseService<PayFlow, String> {

	@Autowired
	@Qualifier("employeeWxService")
	private WxMpService employeeWxService;

	@Autowired
	@Qualifier("vipWxService")
	private WxMpService vipWxService;

	@Autowired
	private VipMapper vipMapper;
	
	@Autowired
	private OrderInfoService orderService;
	
	@Autowired
	private OrderInfoMapper orderInfoMapper;
	
	@Autowired
	private NoteDictMapper dictMapper;

	@Override
	protected PayFlowMapper getBaseMapper() {
		// TODO Auto-generated method stub
		return (PayFlowMapper)baseMapper;
	}

	public PayFlow getByFlowNoAndPayWay(String flowNo,String payWay){
		return this.getBaseMapper().selectByFlowNoAndPayWay(flowNo, Constant.PAY_WAY_ZX);
	}
	
	/**
	 * 微信端消费支付(同步锁)
	 * @param paySource
	 * @param flowNo
	 * @param payOrder
	 * @return
	 */
	public synchronized ResultMsg checkXfWxPayInfo(String flowNo,WxMpPayOrderQuery payOrder){
		PayFlow payFlow = this.getBaseMapper().selectByFlowNoAndPayWay(flowNo, Constant.PAY_WAY_ZX);
		if(payFlow!=null){
			if(!PayResult.SUCCESS.toString().equals(payFlow.getPayResult())){//支付未完成
				if(payOrder==null){
					payOrder = employeeWxService.queryWxPayOrder(flowNo);
				}
				if(StringUtils.isNotEmpty(payOrder.getResult_code())){
					payFlow.setTransactionId(payOrder.getTransaction_id());
					//payFlow.setAmount(new BigDecimal(payOrder.getTotal_fee()).divide(new BigDecimal("100")));
					payFlow.setCompleteTime(DateUtil.str2Date(payOrder.getTime_end(), DateUtil.DATETIMEFORMAT_STR));
					if(StringUtils.isNotEmpty(payOrder.getTrade_state())){
						payFlow.setPayResult(payOrder.getTrade_state());
					}else{
						payFlow.setPayResult(payOrder.getResult_code().equals(Constant.WX_FAIL)?PayResult.PAYERROR.toString():PayResult.SUCCESS.toString());
					}
					if(StringUtils.isNotEmpty(payOrder.getTrade_state_desc())){
						payFlow.setTradeStateDesc(payOrder.getTrade_state_desc());
					}else{
						payFlow.setTradeStateDesc(PayResult.SUCCESS.toString().equals(payFlow.getPayResult())?PayResult.SUCCESS.getName():PayResult.PAYERROR.getName());
					}

					this.getBaseMapper().updateByPrimaryKey(payFlow);

					if(PayResult.SUCCESS.toString().equals(payFlow.getPayResult())){
						OrderInfo orderInfo = this.orderService.getByOrderNo(flowNo);
						orderInfo.setDetailList(this.orderService.getDetails(orderInfo.getOrderInfoId()));
						this.orderService.saveOrderPay(orderInfo, Constant.PAY_WAY_ZX, null);
					}
				}else{//查询失败
					return ResultMsgFactory.fail("未找到支付记录，有疑问请联系客服");
				}
			}
			if(PayResult.SUCCESS.toString().equals(payFlow.getPayResult())){//支付成功
				ResultMsg resultMsg = ResultMsgFactory.successMsg();
				return resultMsg;
			}else if(PayResult.USERPAYING.toString().equals(payFlow.getPayResult())){
				return ResultMsgFactory.fail("正在支付中，请稍后查询");
			}else{
				return ResultMsgFactory.fail("支付失败，请稍后重试");
			}
		}else{//未找到
			return ResultMsgFactory.fail("未找到支付记录，有疑问请联系客服");
		}
	}
	
	/**
	 * 微信端会员充值(同步锁)
	 * @param paySource
	 * @param flowNo
	 * @param payOrder
	 * @return
	 */
	public synchronized ResultMsg checkCzWxPayInfo(String flowNo,WxMpPayOrderQuery payOrder){
		PayFlow payFlow = this.getBaseMapper().selectByFlowNoAndPayWay(flowNo, Constant.PAY_WAY_ZX);
		if(payFlow!=null){
			if(StringUtils.isEmpty(payFlow.getPayResult())){//支付未完成
				if(payOrder==null){
					payOrder = vipWxService.queryWxPayOrder(flowNo);
				}
				if(StringUtils.isNotEmpty(payOrder.getResult_code())){
					payFlow.setTransactionId(payOrder.getTransaction_id());
					payFlow.setAmount(new BigDecimal(payOrder.getTotal_fee()).divide(new BigDecimal("100")));
					payFlow.setCompleteTime(DateUtil.str2Date(payOrder.getTime_end(), DateUtil.DATETIMEFORMAT_STR));
					if(StringUtils.isNotEmpty(payOrder.getTrade_state())){
						payFlow.setPayResult(payOrder.getTrade_state());
					}else{
						payFlow.setPayResult(payOrder.getResult_code().equals(Constant.WX_FAIL)?PayResult.PAYERROR.toString():PayResult.SUCCESS.toString());
					}
					if(StringUtils.isNotEmpty(payOrder.getTrade_state_desc())){
						payFlow.setTradeStateDesc(payOrder.getTrade_state_desc());
					}else{
						payFlow.setTradeStateDesc(PayResult.SUCCESS.toString().equals(payFlow.getPayResult())?PayResult.SUCCESS.getName():PayResult.PAYERROR.getName());
					}

					this.getBaseMapper().updateByPrimaryKey(payFlow);

					//订单支付
					if(PayResult.SUCCESS.toString().equals(payFlow.getPayResult())){
						NoteDict dict = this.dictMapper.selectVipRechargeRule(payFlow.getCompId(), payFlow.getAmount());
						BigDecimal totalAmount = payFlow.getAmount();
						if(dict!=null&&StringUtils.isNotEmpty(dict.getVal2())){
							BigDecimal giveAmount = new BigDecimal(dict.getVal2());
							totalAmount = totalAmount.add(giveAmount);
						}
						this.vipMapper.updateBalance(payFlow.getVipId(), totalAmount);
					}
				}else{//查询失败
					return ResultMsgFactory.fail("未找到充值记录，有疑问请联系客服");
				}
			}
			if(PayResult.SUCCESS.toString().equals(payFlow.getPayResult())){//支付成功
				//Map<String, Object> map = new LinkedHashMap<>();
				//map.put("amount", payFlow.getAmount());
				ResultMsg resultMsg = ResultMsgFactory.successMsg();
				//				resultMsg.setParams(map);
				return resultMsg;
			}else if(PayResult.USERPAYING.toString().equals(payFlow.getPayResult())){
				return ResultMsgFactory.fail("正在充值中，请稍后查询");
			}else{
				return ResultMsgFactory.fail("充值失败，请稍后重试");
			}
		}else{//未找到
			return ResultMsgFactory.fail("未找到充值记录，有疑问请联系客服");
		}
	}

	/**
	 * 后台会员充值
	 * @param vipId
	 * @param amount 充值金额
	 */
	public void updateVipBalance(String compId,String vipId,BigDecimal amount){
		PayFlow payFlow = new PayFlow();
		payFlow.setPayFlowId(CodecUtils.getUUID());
		payFlow.setCompId(compId);
		payFlow.setVipId(vipId);
		payFlow.setFlowNo(CodecUtils.getRechargeNo());
		payFlow.setAmount(amount);
		payFlow.setPaySource(Constant.PAY_SOURCE_CZ);
		payFlow.setPayWay(Constant.PAY_WAY_XJ);
		payFlow.setStatedate(new Date());
		payFlow.setCompleteTime(new Date());
		payFlow.setPayResult(PayResult.SUCCESS.toString());
		payFlow.setTradeStateDesc("充值成功");

		this.save(payFlow);
		
		NoteDict dict = this.dictMapper.selectVipRechargeRule(compId, amount);
		BigDecimal totalAmount = payFlow.getAmount();
//		if(dict!=null&&StringUtils.isNotEmpty(dict.getVal2())){
//			BigDecimal giveAmount = new BigDecimal(dict.getVal2());
//			totalAmount = totalAmount.add(giveAmount);
//		}
		this.vipMapper.updateBalance(payFlow.getVipId(), totalAmount);
	}
	
	 public void save(PayFlow payFlow,OrderInfo orderInfo) {
		 this.baseMapper.insert(payFlow);
		 this.orderInfoMapper.updateByPrimaryKeySelective(orderInfo);
	 }
	 /**
	  * 查询后台会员充值流水信息
	  * @param querier
	  * @param payFlow
	  * @return
	  */
	public Page<PayFlow> queryPayFlowpage(Querier querier, PayFlow payFlow) {
		Page<PayFlow> page = new Page<PayFlow>(querier);
    	List<PayFlow> list = getBaseMapper().queryPayFlowPageFromBack(payFlow, page);
    	page.setRows(list);
        return page;
	}
	/**
	 * 查询汇总信息
	 * @param payFlow
	 * @return
	 */
	public String getpayFlowAmount(PayFlow payFlow) {
		// TODO Auto-generated method stub
		return getBaseMapper().getpayFlowAmount(payFlow);
	}
}
